package com.three.box.network

import com.jiongbull.jlog.JLog
import com.three.box.config.Constant
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


class BManager private constructor() {
    companion object {
        const val TAG = "BManager"
        val instance: BManager by lazy {
            BManager()
        }
    }

    private val mRetrofit by lazy {
        //打印retrofit日志
        val loggingInterceptor = HttpLoggingInterceptor { message: String? ->
            showRetrofitLog(message)
        }.setLevel(HttpLoggingInterceptor.Level.BODY)
        val okHttpClient = OkHttpClient.Builder()
            .readTimeout(30, TimeUnit.SECONDS)
            .connectTimeout(30, TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            .addInterceptor(HeaderInterceptor())
            .build()

        Retrofit.Builder()
            .baseUrl(Constant.BASE_URL) //设置网络请求的Url地址
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build()
    }

    fun <T> create(service: Class<T>?): T {
        if (service == null) {
            throw RuntimeException("Api service is null!")
        }
        return mRetrofit.create(service)
    }

    /**
     * 打印日志
     * 返回的是json，就打印格式化好了的json，不是json就原样打印
     */
    private fun showRetrofitLog(message: String?) {
        if (message == null || message.length > 1000) {
            return
        }
        if (message.startsWith("{")) {
            JLog.json(message)
        } else {
            JLog.e("Retrofit:", message)
        }
    }
}














